﻿using Hangfire;
using Microsoft.Extensions.Logging;

namespace ORS.OrderRobot
{
	public class HangfireBackgroundJobManager: IBackgroundJobManager
    {
        private readonly ILogger<HangfireBackgroundJobManager> _logger;

        public HangfireBackgroundJobManager(ILogger<HangfireBackgroundJobManager> logger)
        {
            _logger = logger;
        }

        public Task EnqueueAsync<TJob, TArgs>(TArgs args, int? delayMinute = null) where TJob : IBackgroundJob<TArgs>
        {
            try
            {
                string queueName = "default";
                var attr = typeof(TArgs).GetCustomAttributes(typeof(BackgroundJobNameAttribute), false).FirstOrDefault() as BackgroundJobNameAttribute;
                if (attr != null)
                {
                    queueName = attr.Name;
                }
                _logger.LogInformation($"Job {typeof(TJob).Name} 已加入执行队列.");
                if (delayMinute != null)
                {
                    BackgroundJob.Schedule<TJob>(job => job.ExecuteAsync(args), TimeSpan.FromMinutes(delayMinute.Value));
                }
                else BackgroundJob.Enqueue<TJob>(job => job.ExecuteAsync(args));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error enqueuing the background job.");
            }

            return Task.CompletedTask;
        }

    }
}

